<template>
  <a-drawer
    title="课件管理"
    :visible="open"
    :mask-closable="false"
    width="634"
    @close="onCancel"
  >
    <div class="top-content">
      <p>1.线上课课件调整及时生效，操作不可逆，请谨慎操作。</p>
    </div>
    <div class="float-left mt-24">
      <SelectAttachment
        :default-keys="attachments"
        :open="attachmentVisible"
        @cancel="handleAttachmentCancel"
        @selected="handleAttachmentSelected"
      />
      
      <div v-if="init" class="float-left text-center mt-30">
        <a-spin />
      </div>
      
      <div v-else class="float-left">
        <a-form
          :model="form"
          name="attachment-update-basic"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 19 }"
          autocomplete="off"
          @finish="onFinish"
          @finishFailed="onFinishFailed"
        >
          <div class="c-flex">
            <a-form-item>
              <div class="ml-42">
                <a-button type="primary" @click="handleAddAttachment">
                  添加课件
                </a-button>
              </div>
            </a-form-item>
            <div class="hous-box">
              <span v-if="attachmentData.length === 0" class="no-hours">
                请点击上方按钮添加课件
              </span>
              
              <TreeAttachments
                v-if="attachmentData.length > 0"
                :data="attachmentData"
                @remove-item="handleRemoveItem"
                @update="handleAttachmentsUpdate"
              />
            </div>
          </div>
        </a-form>
      </div>
    </div>
  </a-drawer>
</template>

<script setup>
import { ref, watch, h } from 'vue';
import { Modal, message } from 'ant-design-vue';
import { ExclamationCircleFilled } from '@ant-design/icons-vue';
import { course, courseAttachment } from '@/api';
import SelectAttachment from '@/components/Common/select-attachment.vue';
import TreeAttachments from './attachments.vue';

const { confirm } = Modal;

const props = defineProps({
  id: {
    type: Number,
    default: 0
  },
  open: {
    type: Boolean,
    default: false
  },
  onCancel: {
    type: Function,
    default: () => {}
  }
});

const init = ref(true);
const attachmentVisible = ref(false);
const attachmentData = ref([]);
const attachments = ref([]);
const form = ref({});

// 监听props变化
watch(() => [props.id, props.open], () => {
  init.value = true;
  if (props.id === 0) {
    return;
  }
  
  attachmentVisible.value = false;
  attachmentData.value = [];
  attachments.value = [];
  
  if (props.open) {
    getDetail();
  }
}, { immediate: true });

// 获取详情
const getDetail = async () => {
  try {
    const res = await course.course(props.id);
    const treeData = res.data.attachments;
    
    if (treeData.length > 0) {
      const { arr, keys } = resetAttachments(treeData);
      attachmentData.value = arr;
      attachments.value = keys;
    }
    
    init.value = false;
  } catch (error) {
    console.error('获取详情失败:', error);
    init.value = false;
  }
};

// 重置附件数据
const resetAttachments = (data) => {
  const arr = [];
  const keys = [];
  
  if (data) {
    for (let i = 0; i < data.length; i++) {
      arr.push({
        type: data[i].type,
        name: data[i].title,
        rid: data[i].rid,
        id: data[i].id,
      });
      keys.push(data[i].rid);
    }
  }
  
  return { arr, keys };
};

// 表单提交
const onFinish = (values) => {
  // 处理表单提交逻辑
};

const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo);
};

// 选择附件数据
const handleAttachmentSelected = async (arr, videos) => {
  // 过滤掉已经存在的文件，避免重复添加
  const existingRids = attachmentData.value.map(item => item.rid);
  const newVideos = videos.filter(video => !existingRids.includes(video.rid));
  
  if (newVideos.length === 0) {
    message.error('所选文件已存在，请选择其他文件');
    return;
  }
  
  const hours = [];
  
  for (let i = 0; i < newVideos.length; i++) {
    hours.push({
      sort: attachmentData.value.length + i,
      title: newVideos[i].name,
      type: newVideos[i].type,
      rid: newVideos[i].rid,
    });
  }
  
  if (hours.length === 0) {
    message.error('请选择课件');
    return;
  }
  
  try {
    await courseAttachment.storeCourseAttachmentMulti(props.id, hours);
    attachmentVisible.value = false;
    getDetail(); // 重新获取数据，确保数据同步
  } catch (error) {
    console.error('添加课件失败:', error);
    // 如果是因为文件已存在的错误，可以给用户更明确的提示
    if (error.response && error.response.data && error.response.data.message) {
      message.error(error.response.data.message);
    } else {
      message.error('添加课件失败');
    }
  }
};

// 删除附件
const delAttachments = (hid) => {
  const data = [...attachmentData.value];
  
  confirm({
    title: '操作确认',
    icon: () => h(ExclamationCircleFilled),
    content: '确认删除此课件？',
    centered: true,
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      const index = data.findIndex(i => i.rid === hid);
      let delId = data[index]?.id;
      
      if (index >= 0) {
        data.splice(index, 1);
      }
      
      // 同步更新两个数组
      if (data.length > 0) {
        attachmentData.value = data;
        const keys = data.map(item => item.rid);
        attachments.value = keys;
      } else {
        attachmentData.value = [];
        attachments.value = [];
      }
      
      if (delId) {
        try {
          await courseAttachment.destroyAttachment(props.id, delId);
          message.success('删除成功');
        } catch (error) {
          console.error('删除课件失败:', error);
          message.error('删除课件失败');
          // 如果删除失败，重新获取数据恢复状态
          getDetail();
        }
      }
    },
    onCancel() {
      console.log('Cancel');
    },
  });
};

// 转换附件顺序
const transAttachments = async (arr) => {
  attachments.value = arr;
  const data = [...attachmentData.value];
  const newArr = [];
  const hourIds = [];
  
  for (let i = 0; i < arr.length; i++) {
    const item = data.find(item => item.rid === arr[i]);
    if (item) {
      newArr.push(item);
      hourIds.push(item.id);
    }
  }
  
  attachmentData.value = newArr;
  
  try {
    await courseAttachment.transCourseAttachment(props.id, hourIds);
  } catch (error) {
    console.error('更新课件顺序失败:', error);
    // 如果更新失败，重新获取数据恢复状态
    getDetail();
  }
};

// 事件处理函数
const handleAttachmentCancel = () => {
  attachmentVisible.value = false;
};

const handleAddAttachment = () => {
  attachmentVisible.value = true;
};

const handleRemoveItem = (id) => {
  delAttachments(id);
};

const handleAttachmentsUpdate = (arr) => {
  transAttachments(arr);
};
</script>

<style scoped>
.hous-box {
  width: 500.53px;
  min-height: 56px;
  background: #ffffff;
  border-radius: 6px;
  border: 1px solid rgba(0, 0, 0, 0.15);
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  /* Firefox */
  -webkit-box-sizing: border-box;
  /* Safari */
  padding: 8px 8px 0px 8px;
  margin-left: 42px;
  display: flex;
  flex-direction: column;
}

.hous-box .no-hours {
  height: 24px;
  font-size: 14px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.25);
  line-height: 24px;
  margin-top: 8px;
}

.top-content {
  width: 502px;
  height: auto;
  background: rgba(255, 77, 79, 0.1);
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  box-sizing: border-box;
  padding: 8px 16px;
  margin: 0 auto;
}

.top-content p {
  font-size: 14px;
  font-weight: 400;
  color: #ff4d4f;
  line-height: 24px;
  margin: 0;
}

.float-left {
  float: left;
}

.mt-24 {
  margin-top: 24px;
}

.mt-30 {
  margin-top: 30px;
}

.ml-42 {
  margin-left: 42px;
}

.text-center {
  text-align: center;
}

.c-flex {
  display: flex;
  flex-direction: column;
}
</style>